#!/usr/bin/env python3
"""
Build script for creating Windows executable of PDF Splitter.
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path


def run_command(cmd, cwd=None):
    """Run command and return result."""
    print(f"Running: {' '.join(cmd) if isinstance(cmd, list) else cmd}")
    result = subprocess.run(
        cmd,
        cwd=cwd,
        shell=isinstance(cmd, str),
        capture_output=False,
        text=True
    )
    if result.returncode != 0:
        print(f"Command failed with exit code: {result.returncode}")
        sys.exit(1)
    return result


def clean_build_dirs():
    """Clean previous build directories."""
    print("Cleaning previous build directories...")

    dirs_to_clean = ["build", "dist"]
    for dir_name in dirs_to_clean:
        dir_path = Path(dir_name)
        if dir_path.exists():
            print(f"Removing {dir_path}")
            shutil.rmtree(dir_path)


def install_dependencies():
    """Install build dependencies."""
    print("Installing build dependencies...")

    # Check if we're in a UV environment
    if "VIRTUAL_ENV" in os.environ and ".venv" in os.environ.get("VIRTUAL_ENV", ""):
        # Use UV to install PyInstaller
        print("Using UV to install PyInstaller...")
        run_command(["uv", "add", "--dev", "pyinstaller>=6.0.0"])
    else:
        # Use pip to install PyInstaller
        print("Using pip to install PyInstaller...")
        # Try different methods to install
        if os.path.exists(os.path.join(os.path.dirname(sys.executable), "pip.exe")):
            run_command([os.path.join(os.path.dirname(sys.executable), "pip.exe"), "install", "pyinstaller>=6.0.0"])
        else:
            # Fallback to ensurepip
            run_command([sys.executable, "-m", "ensurepip", "--default-pip"])
            run_command([sys.executable, "-m", "pip", "install", "pyinstaller>=6.0.0"])

    # Install UPX for compression (optional but recommended)
    # Note: UPX needs to be downloaded separately from https://upx.github.io/
    # and added to PATH or placed in the project directory


def build_executable():
    """Build the executable using PyInstaller."""
    print("Building executable...")

    # Use the spec file for building
    spec_file = Path("pdf_splitter.spec")
    if not spec_file.exists():
        print(f"Error: Spec file {spec_file} not found!")
        sys.exit(1)

    # Run PyInstaller with the spec file
    run_command([
        sys.executable, "-m", "PyInstaller",
        "--clean",
        "--noconfirm",
        str(spec_file)
    ])

    # Check if executable was created
    exe_path = Path("dist/PDF_Splitter.exe")
    if exe_path.exists():
        print(f"✅ Executable created successfully: {exe_path.absolute()}")
        print(f"Size: {exe_path.stat().st_size / 1024 / 1024:.2f} MB")
    else:
        print("❌ Executable not found!")
        sys.exit(1)


def create_installer_script():
    """Create Inno Setup installer script template."""
    installer_script = Path("PDF_Splitter.iss")

    # Get current directory paths
    current_dir = Path.cwd()
    exe_path = current_dir / "dist" / "PDF_Splitter.exe"

    if not exe_path.exists():
        print("❌ Executable not found, cannot create installer script!")
        return

    # Create Inno Setup script
    iss_content = f"""; PDF Splitter Installer Script
; Requires Inno Setup 6 or later to compile

[Setup]
AppName=PDF Splitter
AppVersion=0.1.0
AppPublisher=PDF Splitter
AppPublisherURL=https://gitcode.com/beinimaliesi/PDF_Splitter
AppSupportURL=https://gitcode.com/beinimaliesi/PDF_Splitter/issues
AppUpdatesURL=https://gitcode.com/beinimaliesi/PDF_Splitter

DefaultDirName={{autopf}}\\PDF Splitter
DefaultGroupName=PDF Splitter
AllowNoIcons=yes
LicenseFile=COPYING.txt
OutputDir=installer
OutputBaseFilename=PDF_Splitter_Setup_v0.1.0
Compression=lzma2/max
SolidCompression=yes
WizardStyle=modern
PrivilegesRequired=admin

[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
Name: "chineses"; MessagesFile: "compiler:Languages\\ChineseSimplified.isl"

[Tasks]
Name: "desktopicon"; Description: "{{cm:CreateDesktopIcon}}"; GroupDescription: "{{cm:AdditionalIcons}}"; Flags: unchecked

[Files]
Source: "dist\\PDF_Splitter.exe"; DestDir: "{{app}}"; Flags: ignoreversion
; Note: Don't use "Flags: ignoreversion" on any shared system files

[Icons]
Name: "{{group}}\\PDF Splitter"; Filename: "{{app}}\\PDF_Splitter.exe"
Name: "{{commondesktop}}\\PDF Splitter"; Filename: "{{app}}\\PDF_Splitter.exe"; Tasks: desktopicon

[Run]
Filename: "{{app}}\\PDF_Splitter.exe"; Description: "{{cm:LaunchProgram,PDF Splitter}}"; Flags: nowait postinstall skipifsilent

[UninstallDelete]
Type: filesandordirs; Name: "{{app}}"
"""

    with open(installer_script, "w", encoding="utf-8") as f:
        f.write(iss_content)

    print(f"✅ Installer script created: {installer_script.absolute()}")
    print("To create the installer:")
    print("1. Download and install Inno Setup 6 from https://jrsoftware.org/isdl.php")
    print(f"2. Open {installer_script} in Inno Setup Compiler")
    print("3. Click Build or press Ctrl+F9")


def main():
    """Main build process."""
    print("=" * 60)
    print("PDF Splitter Windows Build Script")
    print("=" * 60)

    # Ensure we're in the right directory
    script_dir = Path(__file__).parent
    project_dir = script_dir.parent
    os.chdir(project_dir)

    print(f"Working directory: {Path.cwd()}")

    # Step 1: Clean previous builds
    clean_build_dirs()

    # Step 2: Install dependencies
    install_dependencies()

    # Step 3: Build executable
    build_executable()

    # Step 4: Create installer script
    create_installer_script()

    print("\n" + "=" * 60)
    print("✅ Build completed successfully!")
    print("=" * 60)
    print(f"\nExecutable location: dist/PDF_Splitter.exe")
    print("\nNext steps:")
    print("1. Test the executable to ensure it works correctly")
    print("2. Use Inno Setup to create the installer (see PDF_Splitter.iss)")
    print("3. Test the installer on a clean system")


if __name__ == "__main__":
    main()